#!/usr/bin/octave -q

bearing = str2num(argv(){1});

if isempty(bearing)
  printf('\nUsage: servo.m <bearing>\n\n');
  exit
end

if bearing<5 | bearing>355
  printf('\nBearing must be between 5 and 355 degrees\n\n');
  exit
end

% Servo needs both channels turned on even though 
%  the signal only uses the rigt channel
system('unmute_pulseaudio');
system('alsactl -f ~/.alsa_both restore');

printf('Moving to bearing %d \n',bearing);

fs = 44e3;		% Sampling frequency
dur = 20e-3;		% Signal period
ns = round(fs*dur);	% Number of samples in one period

% 44 samples = 1ms
sample_range = [65, 109];
diff = sample_range(2) - sample_range(1);
pulse_width = round(sample_range(1) + diff*bearing/360);	% Pulse width in samples

sig = -ones(ns,1);
sig(1:pulse_width) = 1;

reps = 150;			% Repetitions of single period
sig = repmat(sig,reps,1);

right_channel = 1;
if (right_channel)
	sig = [ zeros(ns*reps,1) sig];
else
	sig = [ sig zeros(ns*reps,1) ];
end

wavwrite(sig,fs,'out.wav');
sleep(0.1)
system('sudo killall signalgen > /dev/null 2>&1');
system('sudo killall aplay > /dev/null 2>&1');
sleep(1.0)
system('aplay out.wav');% > /dev/null 2>&1 ');
sleep(3.0)
system('sudo killall aplay > /dev/null 2>&1');

%  system('alsactl -f ~/.alsa_both restore');
